<template>
  <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <div class="modal-container" @click.stop>
      <div class="modal-header">
        <h3>历史操作</h3>
        <button class="close-btn" @click="handleClose">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      <div class="modal-body">
        <div class="history-filters">
          <div class="filter-item">
            <label>操作人：</label>
            <input type="text" v-model="filterByUser" placeholder="输入操作人名称" />
          </div>
          <div class="filter-item">
            <label>操作类型：</label>
            <select v-model="filterByType">
              <option value="">全部类型</option>
              <option value="create">创建</option>
              <option value="update">更新</option>
              <option value="approve">审批</option>
              <option value="reject">拒绝</option>
              <option value="transfer">转交</option>
              <option value="complete">完成</option>
            </select>
          </div>
        </div>
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else>
          <div class="history-list">
            <div class="history-item" v-for="(log, index) in filteredLogs" :key="index">
              <div class="log-header">
                <div class="log-user-info">
                  <span class="user-name">{{ log.approverName || log.userName }}</span>
                  <span class="user-role">({{ log.role || log.userRole }})</span>
                </div>
                <div class="log-time">{{ formatTime(log.timestamp) }}</div>
              </div>
              <div class="log-content">
                <span class="operation-type" :class="`type-${log.operationType || 'update'}`">
                  {{ getOperationText(log.operationType || 'update') }}
                </span>
                <span class="status-text">{{ log.statusText }}</span>
              </div>
              <div class="log-details">
                <div class="detail-item">
                  <span class="detail-label">节点名称：</span>
                  <span class="detail-value">{{ log.nodeName }}</span>
                </div>
                <div class="detail-item" v-if="log.flowName">
                  <span class="detail-label">流程名称：</span>
                  <span class="detail-value">{{ log.flowName }}</span>
                </div>
              </div>
              <!-- 解析并渲染comment值为表单组件 -->
              <div v-if="log.comment" class="node-content">
                <div class="content-title">反馈情况：</div>
                  <div class="form-components">
                    <div v-if="isJSON(log.comment)" class="feedback-content">
                      <div v-for="(value, key) in processFeedbackData(log.comment)" :key="key" class="feedback-item">
                        <span class="feedback-key">{{ formatKey(key) }}：</span>
                        <span class="feedback-value" :class="getFeedbackValueClass(key, value)">{{ formatValue(key, value) }}</span>
                      </div>
                    </div>
                    <div v-else class="feedback-content">
                      <div class="feedback-item">
                        <span class="feedback-value">{{ formatValue('', log.comment) }}</span>
                      </div>
                    </div>
                  </div>
              </div>
              <!-- 如果comment为空，显示暂未处理的提示 -->
              <div v-else class="node-content">
                <div class="content-title">反馈情况：</div>
                <div class="form-components">
                  <div class="feedback-content">
                    <div class="feedback-item">
                      <span class="feedback-value">暂未处理</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="filteredLogs.length === 0" class="empty-state">
            暂无操作记录
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="handleClose">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import taskApprovalService from '../services/taskApprovalService';

export default {
  name: 'TaskHistoryLogModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    taskId: {
      type: [String, Number],
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const historyLogs = ref([]);
    const filterByUser = ref('');
    const filterByType = ref('');
    const loading = ref(false);

    // 获取历史操作数据 - 接入真实API
    const fetchHistoryLogs = async () => {
      if (!props.taskId) {
        console.warn('Task ID is required to fetch history logs');
        return;
      }

      loading.value = true;
      try {
        // 调用任务节点详情接口
        const response = await taskApprovalService.getTaskNodeDetails(props.taskId);
        
        // 根据接口响应数据格式化日志
        if (response && response.data) {
          // 假设接口返回的数据格式如下，实际需要根据后端返回格式调整
          // { approvalRecords: [{ approverName, approvalContent, timestamp, ... }] }
          const logs = formatApiResponseToLogs(response.data);
          historyLogs.value = logs;
        } else {
          console.warn('No data returned from API');
          historyLogs.value = [];
        }
      } catch (error) {
        console.error('Failed to fetch task history logs:', error);
        // 如果API调用失败，使用模拟数据作为备选
        historyLogs.value = getMockHistoryLogs();
      } finally {
        loading.value = false;
      }
    };

    // 格式化API响应数据为日志格式
    const formatApiResponseToLogs = (data) => {
      // 检查数据是否有效
      if (!data || !Array.isArray(data)) {
        return [];
      }

      return data.map((record, index) => {
        // 直接返回记录数据，确保包含所有需要的字段
        return {
          id: index + 1,
          statusText: record.statusText || '',
          nodeName: record.nodeName || '',
          role: record.role || '',
          nodeContent: record.nodeContent || '',
          comment: record.comment || '', // 确保comment字段被正确获取
          approverName: record.approverName || '未知用户',
          flowName: record.flowName,
          timestamp: record.timestamp || new Date().toISOString(),
          operationType: 'update' // 默认设置为更新类型
        };
      });
    };

    // 解析nodeContent字符串为表单组件对象
    const parseNodeContent = (nodeContentStr) => {
      if (!nodeContentStr || typeof nodeContentStr !== 'string') {
        return [];
      }

      try {
        // 处理字符串格式，将=替换为:，使其成为有效的JSON格式
        const jsonStr = nodeContentStr
          .replace(/=/g, ':')
          .replace(/\s+/g, '')
          .replace(/'/g, '"')
          .replace(/,([^\s])/g, ', $1');

        // 解析JSON字符串
        const components = JSON.parse(jsonStr);
        return Array.isArray(components) ? components : [components];
      } catch (error) {
        console.error('解析nodeContent失败:', error);
        return [];
      }
    };

    // 模拟历史操作数据 - 作为API调用失败时的备选
    const getMockHistoryLogs = () => {
      return [
        {
          id: 1,
          statusText: "处理中",
          nodeName: "测试节点一",
          role: "测试角色",
          nodeContent: '[{"id":"radio_1757315551442","icon":"🔘","name":"是否通过","type":"radio","label":"是否通过","width":"100%","options":[{"label":"通过","value":"1"},{"label":"不通过","value":"2"}],"required":false}]',
          approverName: "刘德华",
          flowName: null,
          timestamp: '2024-01-15 10:30:00'
        },
        {
          id: 2,
          statusText: "待处理",
          nodeName: "测试节点二",
          role: "管理员角色",
          nodeContent: '[{"id":"select_1757315551443","name":"处理方式","type":"select","label":"处理方式","width":"100%","options":[{"label":"正常处理","value":"normal"},{"label":"加急处理","value":"urgent"}],"required":true}]',
          approverName: "张学友",
          flowName: "审批流程A",
          timestamp: '2024-01-15 14:25:00'
        }
      ];
    };

    // 过滤后的日志
    const filteredLogs = computed(() => {
      return historyLogs.value.filter(log => {
        const userMatch = filterByUser.value ? 
          log.userName.includes(filterByUser.value) : true;
        const typeMatch = filterByType.value ? 
          log.operationType === filterByType.value : true;
        return userMatch && typeMatch;
      });
    });

    // 获取操作类型文本
    const getOperationText = (type) => {
      const operationMap = {
        'create': '创建',
        'update': '更新',
        'approve': '审批通过',
        'reject': '拒绝',
        'transfer': '转交',
        'complete': '完成'
      };
      return operationMap[type] || type;
    };

    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      try {
        const date = new Date(timeStr);
        return date.toLocaleString('zh-CN');
      } catch (error) {
        return timeStr;
      }
    };

    // 处理关闭
    const handleClose = () => {
      // 重置筛选条件
      filterByUser.value = '';
      filterByType.value = '';
      emit('close');
    };

    // 处理遮罩层点击
    const handleOverlayClick = () => {
      handleClose();
    };

    // 监听visible和taskId的变化，当模态框显示或任务ID变化时重新获取数据
    watch(
      () => [props.visible, props.taskId],
      ([newVisible, newTaskId]) => {
        if (newVisible && newTaskId) {
          fetchHistoryLogs();
        }
      },
      { immediate: true }
    );

    // 检查字符串是否为有效的JSON格式
    const isJSON = (str) => {
      if (!str || typeof str !== 'string') {
        return false;
      }
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    };

    // 处理反馈数据，解析JSON并返回对象
    const processFeedbackData = (jsonStr) => {
      try {
        const parsed = JSON.parse(jsonStr);
        return parsed;
      } catch (e) {
        console.error('解析反馈数据失败:', e);
        return {};
      }
    };

    // 格式化键名，使其更易读
    const formatKey = (key) => {
      // 这里可以根据需要添加更多的格式化规则
      if (key.includes('是否通过')) {
        return '是否通过';
      }
      return key;
    };

    // 格式化值，特别是处理"是否通过"字段、多行文本和去除特殊符号
    const formatValue = (key, value) => {
      // 处理是否通过字段
      if (key.includes('是否通过') || key === '是否通过') {
        if (value === '1' || value === 1) {
          return '通过';
        } else if (value === '2' || value === 2) {
          return '不通过';
        }
      }
      
      // 处理多行文本和去除括号引号等特殊符号
      let formattedValue = value;
      
      // 如果是数组类型，递归处理每个元素
      if (Array.isArray(formattedValue)) {
        // 将数组转换为字符串并用换行符连接，同时去除所有特殊符号
        formattedValue = formattedValue.map(item => formatValue('', item)).join('\n');
      }
      // 如果是对象类型，递归处理每个值
      else if (typeof formattedValue === 'object' && formattedValue !== null) {
        // 将对象的每个值处理后用换行符连接
        formattedValue = Object.values(formattedValue)
          .map(item => formatValue('', item))
          .filter(val => val.trim() !== '')
          .join('\n');
      }
      // 如果是字符串类型，直接处理
      else if (typeof formattedValue === 'string') {
        // 去除括号、引号等特殊符号
        formattedValue = formattedValue.replace(/[\[\]\(\)"'{}]/g, '');
        // 替换逗号或分号为换行符（适用于多条信息的情况）
        formattedValue = formattedValue.replace(/[,;]/g, '\n');
        // 处理可能的换行符
        formattedValue = formattedValue.split('\n').filter(line => line.trim() !== '').join('\n');
      }
      
      return formattedValue;
    };

    // 根据键和值获取样式类
    const getFeedbackValueClass = (key, value) => {
      if (key.includes('是否通过') || key === '是否通过') {
        if (value === '1' || value === 1) {
          return 'status-approved';
        } else if (value === '2' || value === 2) {
          return 'status-rejected';
        }
      }
      return '';
    };

    return {
      historyLogs,
      filteredLogs,
      filterByUser,
      filterByType,
      loading,
      getOperationText,
      formatTime,
      handleClose,
      handleOverlayClick,
      parseNodeContent,
      isJSON,
      processFeedbackData,
      formatKey,
      formatValue,
      getFeedbackValueClass
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 700px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.history-filters {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 6px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.filter-item input,
.filter-item select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
}

.filter-item input:focus,
.filter-item select:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.log-user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.user-role {
  font-size: 12px;
  color: #999;
}

.log-time {
  font-size: 12px;
  color: #999;
}

.log-content {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.operation-type {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  min-width: 60px;
  text-align: center;
}

.type-create {
  background-color: #e6f7ff;
  color: #1890ff;
}

.type-update {
  background-color: #fff7e6;
  color: #fa8c16;
}

.type-approve {
  background-color: #f6ffed;
  color: #52c41a;
}

.type-reject {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.type-transfer {
  background-color: #f9f0ff;
  color: #722ed1;
}

.type-complete {
  background-color: #e6fffb;
  color: #13c2c2;
}

.operation-detail {
  font-size: 14px;
  color: #333;
}

.log-changes {
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.changes-title {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.change-item {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  font-size: 13px;
  margin-bottom: 4px;
}

.change-item:last-child {
  margin-bottom: 0;
}

.change-field {
  color: #666;
  font-weight: 500;
  min-width: 80px;
}

.change-from {
  color: #ff4d4f;
}

.change-arrow {
  color: #999;
  font-weight: 600;
}

.change-to {
  color: #52c41a;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #40a9ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.btn-default {
  background-color: #fff;
  color: #666;
  border-color: #d9d9d9;
}

.btn-default:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

@media (max-width: 768px) {
  .history-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .filter-item input,
  .filter-item select {
    flex: 1;
    min-width: auto;
  }
  
  .log-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .log-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .operation-type {
    align-self: flex-start;
  }
  
  .change-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

/* 反馈情况样式 */
.feedback-content {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 8px;
}

.feedback-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e9ecef;
}

.feedback-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.feedback-key {
  font-weight: 600;
  color: #666;
  min-width: 100px;
  flex-shrink: 0;
  padding-right: 12px;
}

.feedback-value {
    flex: 1;
    color: #333;
    word-break: break-word;
    line-height: 1.5;
    white-space: pre-line; /* 确保换行符能够正确显示 */
  }

/* 状态样式 */
.status-approved {
  color: #52c41a;
  font-weight: 500;
}

.status-rejected {
  color: #ff4d4f;
  font-weight: 500;
}

/* 响应式调整 - 反馈情况 */
@media (max-width: 768px) {
  .feedback-item {
    flex-direction: column;
  }
  
  .feedback-key {
    min-width: auto;
    margin-bottom: 4px;
  }
}</style>